package com.jiuye.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuye.common.BaseContext;
import com.jiuye.common.CustomException;
import com.jiuye.entity.*;
import com.jiuye.mapper.IOrderMapper;
import com.jiuye.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单业务层实现类
 *
 * @author likeWen
 * @since 2022/11/7 17:20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<IOrderMapper, Orders>implements IOrderService {
    //地址
    @Autowired
    private IAddressBookService addressBookService;
    //购物车
    @Autowired
    private IShoppingCartService shoppingCartService;
    //用户
    @Autowired
    private IUserService userService;
    //保存订单明细
    @Autowired
    private IOrderDetailService orderDetailService;
    /**
     * 下单
     * @param orders
     */
    @Override
    @Transactional//多表操作，开启事务
    public void submit(Orders orders) {
        //1.查询地址数据
        AddressBook addressBook = this.addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null){
            throw new CustomException("传入的参数有误");
        }
        //2.查询购物车数据
        LambdaQueryWrapper<ShoppingCart> shoppingCartWrapper = new LambdaQueryWrapper<>();
        shoppingCartWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentUserId());
        List<ShoppingCart> shoppingCartList = this.shoppingCartService.list(shoppingCartWrapper);

        if (CollectionUtils.isEmpty(shoppingCartList)){
            throw new CustomException("购物车为空，不能下单");
        }
        // 3.组装订单明细,并给订单明细表中的主表id赋值，使其与主表产生关系
        long orderId = IdWorker.getId();
        Integer totalAmount = 0;
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orderId);
            // 4.计算订单总价值
            // 单个商品总价 = 单价 * 数量
            BigDecimal price = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber()));
            totalAmount += price.intValue();
            orderDetailList.add(orderDetail);
        }
        // 5.组装订单
        //主表
        Orders ordersMain = new Orders();
        //主表id
        ordersMain.setId(orderId);
        //订单号
        ordersMain.setNumber(orderId + "");
        //订单状态
        ordersMain.setStatus(2);
        //当前用户id
        ordersMain.setUserId(BaseContext.getCurrentUserId());
        //当前订单派送地址
        ordersMain.setAddressBookId(orders.getAddressBookId());
        //订单时间
        ordersMain.setOrderTime(LocalDateTime.now());
        //结账时间
        ordersMain.setCheckoutTime(LocalDateTime.now());
        //支付方式
        ordersMain.setPayMethod(orders.getPayMethod());
        //订单的总价值
        ordersMain.setAmount(new BigDecimal(totalAmount));
        //备注
        ordersMain.setRemark(orders.getRemark());
        //用户名
        User user = userService.getById(BaseContext.getCurrentUserId());
        ordersMain.setUserName(user.getName());
        //收货人的手机号
        ordersMain.setPhone(addressBook.getPhone());
        ordersMain.setAddress(addressBook.getDetail());
        ordersMain.setConsignee(addressBook.getConsignee());
        //6.保存订单
        this.save(ordersMain);
        //7.保存订单明细
        this.orderDetailService.saveBatch(orderDetailList);
        //8.删除购物车数据
        this.shoppingCartService.remove(shoppingCartWrapper);
    }
}
